package org.example.algorithm.linkedlist;

public class IsPalindromeSolution {

    public boolean isPalindrome(ListNode head) {
        if (head == null) {
            return true;
        }
        ListNode slow = head;
        ListNode fast = head;
        //找到中间节点
        while (fast.next != null && fast.next.next != null) {
            slow = slow.next;
            fast = fast.next.next;
        }
        //翻转后半部分
        ListNode newHead = reverse(slow.next);
        ListNode preHalf = head;
        ListNode nextHalf = newHead;
        //判断回文
        while (nextHalf != null) {
            if (nextHalf.val != preHalf.val) {
                return false;
            }
            preHalf = preHalf.next;
            nextHalf = nextHalf.next;
        }
        //恢复后半部分
        slow.next = reverse(newHead);
        return true;
    }

    private ListNode reverse(ListNode node) {
        ListNode newHead = null;
        ListNode cur = node;
        while (cur != null) {
            ListNode temp = cur.next;
            cur.next = newHead;
            newHead = cur;
            cur = temp;
        }
        return newHead;
    }
}
